package com.detect.service.service;

import com.alibaba.fastjson2.JSON;
import com.detect.common.property.ObjectProperties;
import com.detect.common.utils.HttpUtil;
import com.detect.model.vo.ObjectVO;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import okhttp3.*;
import javax.annotation.Resource;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

/**
 * 物体识别服务
 *
 * @author zhulj
 * @since 2024/6/13 15:11
 **/
@Slf4j
@Service
public class ObjectService {

    @Resource
    private ObjectProperties properties;

    @SneakyThrows
    public ObjectVO object(String img) {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        // String base64 = this.getFileContentAsBase64(file, true);
        String base64 = img.replace("/", "%2F");
        base64 = base64.replace("+", "%2B");
        RequestBody body = RequestBody.create(mediaType, "image=" + base64);
        String url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/animal?access_token=" + this.getAccessToken();
        Response response = HttpUtil.post(url, body);
        String result = response.body().string();
        log.info("*******百度识别返回：{}", result);
        return JSON.parseObject(result, ObjectVO.class);
    }

    /**
     * 获取文件base64编码
     *
     * @param path      文件路径
     * @param urlEncode 如果Content-Type是application/x-www-form-urlencoded时,传true
     * @return base64编码信息，不带文件头
     * @throws IOException IO异常
     */
    @SneakyThrows
    public String getFileContentAsBase64(String path, boolean urlEncode) {
        byte[] b = Files.readAllBytes(Paths.get(path));
        String base64 = Base64.getEncoder().encodeToString(b);
        if (urlEncode) {
            base64 = URLEncoder.encode(base64, "utf-8");
        }
        return base64;
    }

    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    @SneakyThrows
    public String getAccessToken() {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + properties.getClientId()
                + "&client_secret=" + properties.getClientSecret());
        String url = "https://aip.baidubce.com/oauth/2.0/token";
        Response response =  HttpUtil.post(url, body);
        return new JSONObject(response.body().string()).getString("access_token");
    }

}
